<?php

namespace app\http\middleware;

use app\hander\HelpHander;
use app\repositories\UserRepository;

class Login
{
	public function handle($request, \Closure $next)
	{
		$token     = $request->token;
		$osType    = $request->ostype;
		$cacheData = cache('token:' . $osType . ':' . $token);
		if (!$cacheData) {
			HelpHander::Response('您还未登录或登录已失效', 401);
		}
		$dbData = UserRepository::find($cacheData['id']);
		if (!$dbData) {
			HelpHander::Response('账号信息不存在', 400);
		}
		if ($dbData['status'] == 2) {
			HelpHander::Response('您的账号已被禁用', 401);
		}
		if ($dbData[$osType . '_token'] !== $token) {
			HelpHander::Response('您已经在其他设备登录', 401);
		}
		$request->userId         = $dbData['id'];
		$request->userInfo       = $dbData;
		$dbData['activity_time'] = time();
		//自动更新过期时间
		cache('token:' . $osType . ':' . $token, $dbData, config('app.user_overtime'));
		return $next($request);
	}
}
